<template>
  <div class="page white-stage">
    <div class="order-audition-main">
      <group class="no-margin">
        <cell title="预约时间" :value="orderAudition.will_attend_time"></cell>
        <cell title="选择预约方式" :value="getOrderWay(orderAudition.will_attend_type)"></cell>
        <cell direction="rtl" title="接待人" placeholder="请选择接待人" :options="receiver" v-model="orderAudition.assist_user" placeholder-align="right"></cell>
        <cell direction="rtl" title="预估成交金额" placeholder="填写预估成交金额" :options="amounts" v-model="orderAudition.estimate_amount" placeholder-align="right" ></cell>
      </group>
      <div class="btn-group center-btn-group">
        <!-- <span class="btn save-btn scrm-default-btn" @click="saveAppointments">保存</span> -->
      </div>
    </div>
    <popup v-model="show" @on-hide="handlePopup('hide')" @on-show="handlePopup('show')" height="100%" style="background-color:white;">
      <div class="empty-btn-cell" @click="show = false"><span class="empty-btn btn">- 取消</span></div>
      <div v-if="show === true" style="background-color:white;height:100%;">
        <div  style="top:60px;" class="pdscroll" :class="{'none':!teamsMembers.length}" :on-infinite="loadMember" :on-refresh="refreshMember" ref="team_scroller" :noDataText="tnoDataText">
          <team-member-item @on-click="memberSelect" v-for="(teamMemberItem, index) in teamsMembers" :key="index" :client="teamMemberItem"></team-member-item>
        </div>
      </div>
    </popup>
    <x-dialog v-model="this.$store.state.app.dialogShow" >
      <div class="dialog-message">
        {{ this.$store.state.app.dialogMessage }}
      </div>
      <span class="vux-close" @click="hideDialog">知道了</span>
    </x-dialog>
  </div>
</template>

<script>
  // import Vue from 'vue'
  // import clientMenu from '../components/client-menu'
  // import {XInput, Group, ChinaAddressData, XAddress, Selector, Datetime, Cell} from 'vux'
  import XInput from 'vux/src/components/x-input'
  import Group from 'vux/src/components/group'
  import XAddress from 'vux/src/components/x-address'
  import ChinaAddressData from 'vux/src/datas/china_address.json'
  import Selector from 'vux/src/components/selector'
  import Datetime from 'vux/src/components/datetime'
  import XDialog from 'vux/src/components/x-dialog'
  import Popup from 'vux/src/components/popup'
  import Cell from 'vux/src/components/cell'
  import store from '../store'
  // import Scroller from 'vue-scroller'
  // import {Popup, XDialog} from 'vux'
  import {showDialog, hideDialog} from '../lib/dialog'
  import teamMemberItem from '../components/team-member-item'
  import { mapActions } from 'vuex'

  export default{
    data () {
      return {
        containerHeight : 'height:'+document.body.scrollHeight+'px;',
        default:{
          ordertime: '',
          orderwayValue: '',
          receiverValue: '',
          amountValue: '',
        },
        teamsMembers: [],
        page_size: 15,
        tnoDataText:'',
        team_page_index: 1,
        show: false,
        babies:[],
        addressData : ChinaAddressData,
        orderAudition:{

        },
        // clientSourceValue: '',
        // industryValue: '',
        // orderAuditionGenderValue: '',

        orderways: [
          {
            key : 'WX#',
            value: '微信'
          },
          {
            key : 'XX#',
            value: '线下'
          }
        ],

        receiver : [

        {
          key: '0',
          value:'林丽亲'
        },

        {
          key:'1',
          value:'李美英'}
        ],

        amounts : [

        {
          key: '0',
          value:'100'
        },

        {
          key:'1',
          value:'50'
        }
        ]
      }
    },
    components:{
      XInput,
      Group,
      ChinaAddressData,
      XAddress,
      Selector,
      Datetime,
      Cell,
      // Scroller,
      Popup,
      teamMemberItem,
      XDialog
    },
    methods: {
      refresh (iscroll) {
        console.log('refresh')
      // Refresh current data
      },

      log () {
        console.log('ee');
      },

      getOrderWay (orderWay) {
        let value = ''
        console.log(this.orderways, orderWay)
        this.orderways.forEach((elem, index) => {
          console.log(elem.value, elem.key, orderWay)
          if (elem.key === orderWay) {
            value = elem.value
          }
        })
        return value
      },

      load (iscroll) {
        console.log('load')
      // Load new data
      },

      test () {
        console.log('test')
      },

      memberSelect(member) {
        console.log('memberSelect: ', member.suid);
        this.setAssist(member)
        this.show = false;
      },


      loadMember(iscroll) {
        console.log('loadMember')
        this.loadMembers({page_index:1});
        // Load new data
      },


      hideDialog: hideDialog,

      refreshMember(iscroll) {
        console.log('refreshMember')
        this.loadMembers();
      },

      hidePopup() {
        this.show = false;
        console.log('hidePopup')
      },

      onBlur () {

      },

      onShow () {
        console.log(arguments)
      },

      addorderAudition () {
        this.babies.push(this.default)
      },

      handlePopup(status) {

        if (status === 'show') {
          // setTimeout(() => {
          //   if(this.$refs.team_scroller) {
          //     this.$refs.team_scroller.resize()
          //   }
          // },200)
        } else {
        }
      },

      onItemClick(clientID) {
        this.loadMembers();
        this.show = true;
        this.selectedClientId = clientID;
        console.log('clientID: ', clientID);
      },

      saveAppointments() {
        let that = this;
        console.log('this.orderAudition',this.orderAudition)
        // alert('预约试听成功!');
        // this.$router.back();
        this.$vux.loading.show({text:'loading'})

        store.dispatch('saveAppointments', this.orderAudition)
          .then(function(response){
            if(response.data.errcode == 0 ) {
              showDialog('预约试听成功!');
              setTimeout(() => {that.$router.back()}, 3000)
            } else {
              showDialog('系统错误！请联系管理员!');
            }
            this.$vux.loading.hide()
        }).catch((e) => {
          this.$vux.loading.hide()
        })
      },

      loadMembers(data) {

        let that = this;
        let params = {
          page_index: this.team_page_index,
          page_size: this.page_size,
          source: 'webapp'
        };

        params = Object.assign(params, data)
        store.dispatch('getTeams', params).then((response) => {

          setTimeout(() => {
            if (typeof response.data.results.teams !== 'undefined') {
              let teams = response.data.results.teams;
              that.filterUserFromTeam(teams);
            } else {
              console.log(that.teamsMembers)
            }

            this.endTeamLoading()

            that.team_page_index++;

          }, 800)

        }).catch((e) => {
          console.log(e)
          this.endTeamLoading()
        })
      },
      //从接口中筛选出团队信息
      filterUserFromTeam(teams) {
        let temps = [];

        if(!this.existMemberIDs) this.existMemberIDs = []

        teams.forEach((team, index) => {
          // if(team.team_managers[0].suid === this.loginUser.id) {
            team.team_members.forEach((member, mindex) => {
              if(this.existMemberIDs.indexOf(member.suid) === -1)  {
                member.team_name = team.team_name;
                temps.push(member);
                this.existMemberIDs.push(member.suid)
              }
            });
          // }
        });
        this.teamsMembers = this.teamsMembers.concat(temps);
        this.setAssist()
      },

      setAssist (member) {
        if(!member) {
          this.orderAudition.assist_user = this.loginUser.name;
          this.orderAudition.assist_suid = this.loginUser.id;
        } else {
          this.orderAudition.assist_user = member.name;
          this.orderAudition.assist_suid = member.suid;
        }
      },

      endTeamLoading() {
        let that = this
        setTimeout(() =>{
          if (that.$refs.team_scroller) {
            that.$refs.team_scroller.finishInfinite(true);
            that.$refs.team_scroller.finishPullToRefresh();
            if (that.teamsMembers.length > 0) {
              that.tnoDataText = ''
            }
            // setTimeout(() => {
            //   if(this.$refs.team_scroller) {
            //     this.$refs.team_scroller.resize()
            //   }
            // },200)
          }
        }, 1000)
      },

      ...mapActions({
        getAppointments: 'getAppointments'
      })

    },


    watch:{
      ordertimeValue(value){
        this.orderAudition.ordertime = value;
      },
      orderwayValue(value){
        this.orderAudition.orderway = value;
      },
      receiverValue(value){
        this.orderAudition.receiver = value;
      },
      amountValue(value){
        this.orderAudition.amount = value;
      },
    },

    computed:{
      loginUser () {
        return this.$store.state.app.user;
      }
    },

    mounted () {
      let query = this.$route.query;
      this.orderAudition.custom_id = query.id;
      let clueId = query.clue_id
      if (clueId) {
        this.$vux.loading.show({text: '加载中....'})
        this.getAppointments(clueId).then((response) => {
          if (response.data.errcode === 0) {
            let orderAudition = response.data.results
            orderAudition.assist_user = orderAudition.assist_name
            this.orderAudition = Object.assign({}, this.orderAudition, orderAudition)
          }
          this.$vux.loading.hide()
        }).catch((error) => {
          this.$vux.loading.hide()
          console.log(error)
        })
      }
      // this.orderAudition.assist_suid = this.loginUser.ding_user_id;
      this.loadMembers()
      this.callJsApi('biz.navigation.setTitle',{title: '约试听'});
      this.addorderAudition();
    },


  }
</script>

<style lang='less'>
  @import "../less/index.less";

  .order-audition-main{

    .no-margin{
       &>*{
       margin: 0
       }
    }

    .add-new-btn{
      width: 60%;
    }



    .btn-group{
      margin-top: 15px;

      &>*{
        width: 80%;
        text-align: center;
        border-radius: 4px;
        padding: 10px;
        margin: 0 auto;
        display: block;
      }

      .pull-left{
        float: left;
      }

      .pull-right{
        float: right;
      }

    }
  }

  .empty-btn.btn{
    display: block;
    color: #39ADFF;
    padding: 10px;
  }

  .empty-btn-cell {
    border: 1px solid #39ADFF;
    width: 90%;
    margin: 0 auto;
    border-radius: 4px;
    display: block;
    margin-top: 10px;
  }

</style>
